package com.fullertontech.framework.logger;

import java.nio.charset.Charset;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.Filter.Result;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.appender.ConsoleAppender.Target;
import org.apache.logging.log4j.core.appender.RollingFileAppender;
import org.apache.logging.log4j.core.appender.rolling.TimeBasedTriggeringPolicy;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.filter.ThresholdFilter;
import org.apache.logging.log4j.core.impl.Log4jContextFactory;
import org.apache.logging.log4j.core.layout.PatternLayout;
import org.apache.logging.log4j.spi.StandardLevel;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import com.fullertontech.framework.global.GlobalUtils;

public class LoggerConfig implements ApplicationContextInitializer<ConfigurableApplicationContext>{
  
  static {
    System.setProperty("org.springframework.boot.logging.LoggingSystem", "Log4J2LoggingSystem");
  }
  
	@Override
	public void initialize(ConfigurableApplicationContext applicationContext) {
		//配置模式方式，这里不适用配置文件方式了
		try {
		  if(GlobalUtils.getAnnotation(EnableLogger.class)==null) {
		    return;
		  }
		  //init();
        } catch (Exception e) {
          e.printStackTrace();
        }
	}
	
	
	public static void init() {
		EnableLogger enableLogger=GlobalUtils.getAnnotation(EnableLogger.class);
		String filePath=null;
		if(enableLogger==null) {
			filePath=EnableLogger.logHome.concat("/").concat(EnableLogger.fileName).concat("/").concat(EnableLogger.fileName);
		}else {
			filePath=enableLogger.logHome().concat("/").concat(enableLogger.fileName()).concat("/").concat(enableLogger.fileName());
		}
		//设置为log4j方式
		LogManager.setFactory(new Log4jContextFactory());
		LoggerContext loggerContext=(LoggerContext) LogManager.getContext(false);
		Configuration configuration=loggerContext.getConfiguration();
		
		PatternLayout patternLayout=PatternLayout.newBuilder()
		.withPattern("%d{yyyy-MM-dd HH:mm:ss,SSS} [%level] [%t] %msg%n")
		.withConfiguration(configuration)
		.withCharset(Charset.forName("utf-8"))
		.withAlwaysWriteExceptions(true)
		.withNoConsoleNoAnsi(false).build();
		
		ConsoleAppender consoleAppender=ConsoleAppender.newBuilder().asBuilder().setLayout(patternLayout)
		.setName("Console").setTarget(Target.SYSTEM_OUT).build();
		
		configuration.addAppender(consoleAppender);
		
		TimeBasedTriggeringPolicy basedTriggeringPolicy=TimeBasedTriggeringPolicy.newBuilder().build();
		ThresholdFilter infoFilter=ThresholdFilter.createFilter(Level.INFO, Result.ACCEPT, Result.DENY);
		
		RollingFileAppender infoLog=RollingFileAppender.newBuilder().asBuilder()
		  .withFileName(filePath+"_info.log")
		  .withFilePattern(filePath+"info.%d{yyyy-MM-dd}.log")
		  .setName("infoLog")
		  .withPolicy(basedTriggeringPolicy)
		  .setLayout(patternLayout)
		  .setFilter(infoFilter)
		  .setConfiguration(configuration).build();
		infoLog.start();
		configuration.addAppender(infoLog);
		
		ThresholdFilter errorFilter=ThresholdFilter.createFilter(Level.ERROR, Result.ACCEPT, Result.DENY);
		RollingFileAppender errorLog=RollingFileAppender.newBuilder().asBuilder()
	          .withFileName(filePath+"_error.log")
	          .withFilePattern(filePath+"error.%d{yyyy-MM-dd}.log")
	          .setName("infoLog")
	          .withPolicy(basedTriggeringPolicy)
	          .setLayout(patternLayout)
	          .setFilter(errorFilter)
	          .setConfiguration(configuration).build();
		errorLog.start();
		configuration.addAppender(errorLog);
		
		ThresholdFilter debugFilter=ThresholdFilter.createFilter(Level.DEBUG, Result.ACCEPT, Result.DENY);
		RollingFileAppender debugLog=RollingFileAppender.newBuilder().asBuilder()
            .withFileName(filePath+"_debug.log")
            .withFilePattern(filePath+"debug.%d{yyyy-MM-dd}.log")
            .setName("debugLog")
            .withPolicy(basedTriggeringPolicy)
            .setLayout(patternLayout)
            .setFilter(debugFilter)
            .setConfiguration(configuration).build();
		debugLog.start();
		configuration.addAppender(debugLog);
		
		ThresholdFilter allFilter=ThresholdFilter.createFilter(Level.ALL, Result.ACCEPT, Result.DENY);
		RollingFileAppender allLog=RollingFileAppender.newBuilder().asBuilder()
            .withFileName(filePath+"_all.log")
            .withFilePattern(filePath+"all.%d{yyyy-MM-dd}.log")
            .setName("allLog")
            .withPolicy(basedTriggeringPolicy)
            .setLayout(patternLayout)
            .setFilter(allFilter)
            .setConfiguration(configuration).build();
		allLog.start();
		configuration.addAppender(allLog);
		
		
		configuration.getRootLogger().addAppender(infoLog, null, null);
		configuration.getRootLogger().addAppender(errorLog, null, null);
		configuration.getRootLogger().addAppender(allLog, null, null);
		configuration.getRootLogger().addAppender(debugLog, null, null);
		configuration.getRootLogger().setLevel(Level.INFO);
		if(enableLogger!=null&&enableLogger.level().equals(StandardLevel.DEBUG)) {
			configuration.getRootLogger().setLevel(Level.valueOf(enableLogger.level().name()));
		}
		
		Configurator.initialize(configuration);
		System.out.println("log4j2加载完毕.......");
	}
}
